<?php
namespace app\manage\controller;

class SystemAdmin extends Base
{
    public function index(){
        if(request()->isAjax()){
            $page = input('page');
            $limit = input('limit');
            $id = input('id');
            $roleId = input('role_id');

            $where = [];
            !empty($id) && $where['id'] = $id;
            !empty($roleId) && $where['roleid'] = $roleId;

            if( ! $count=model('SystemAdmin')->where($where)->count() ){
                $this->layTable();
            }

            $select = model('SystemAdmin')
                ->where($where)
                ->limit(($page-1)*$limit, $limit)
                ->order('id desc')
                ->select();
            $data = collection($select)->append(['role_name']);

            $this->layTable(0, '管理员列表', $data, $count);
        }else{
            $select = model('SystemRole')->field('id, rolename')->select();
            return view('', ['role_id'=>$select]);
        }
    }

    public function add(){
        if( request()->isAjax() ){
            $data = input();
            $addRs = model('SystemAdmin')
                ->validate([
                    'account' => 'unique:systemAdmin',
                    'password'=>'confirm'
                ], [
                    'account.unique' => '账号已存在',
                    'password.confirm' => '两次密码不一致'
                ])->allowField(true)->save( $data );
            $addRs ? $this->layJson(0, '添加成功') : $this->layJson(1, model('SystemAdmin')->getError());
        }else{
            $roleId = model('SystemRole')->field('id, rolename')->select();
            return view('', ['role_id'=>$roleId]);
        }
    }

    public function edit(){
        if( request()->isAjax() ){
            $data = input();
            if(empty($data['password'])) unset($data['password']);

            $editRs = model('SystemAdmin')
                ->validate([
                    'account' => 'unique:systemAdmin',
                    'password'=>'confirm'
                ], [
                    'account.unique' => '账号已存在',
                    'password.confirm' => '两次密码不一致'
                ])->allowField(true)->isUpdate(true)->save( $data );
            $editRs!==false ? $this->layJson(0, '编辑成功') : $this->layJson(1, model('SystemAdmin')->getError());
        }else{
            $find = model('SystemAdmin')->find( input('id') );
            $roleId = model('SystemRole')->field('id, rolename')->select();
            return view('', ['find'=>$find, 'role_id'=>$roleId]);
        }
    }

    public function del(){
        model('SystemAdmin')->destroy(input('id')) ? $this->layJson(0, '删除成功') : $this->layJson(1, '删除失败，请重试');
    }
}